{% extends "admin42/platformmgr/base.html" %}
{% load admin_utils %}
{% block main_content %}
<div id="builtin-config-var-list" class="p20">
    <bk-alert type="warning" title="此处定义的环境变量会覆盖系统内置环境变量。云原生应用环境变量优先级（由高到低）：平台管理自定义环境变量 > 系统内置环境变量 > 单个应用中自定义环境变量"></bk-alert>

    <bk-button theme="primary" class="mb20" @click="handleCreate">
        新建
    </bk-button>

    <bk-table :data="data">
        <bk-table-column label="Key" prop="key" width="500" :formatter="addPrefix" show-overflow-tooltip="true"></bk-table-column>
        <bk-table-column label="Value" prop="value" width="500" show-overflow-tooltip="true"></bk-table-column>
        <bk-table-column label="描述" prop="description" width="500" show-overflow-tooltip="true"></bk-table-column>
        <bk-table-column label="更新时间" prop="updated" width="250" show-overflow-tooltip="true"></bk-table-column>
        <bk-table-column label="更新者" prop="operator" width="200" show-overflow-tooltip="true"></bk-table-column>
        <bk-table-column label="操作" width="200">
            <template slot-scope="props">
                <bk-button class="ml5" theme="primary" text @click="handleEdit(props.row)">编辑</bk-button>
                <bk-button class="ml5" theme="danger" text @click="handleDelete(props.row)">删除</bk-button>
            </template>
        </bk-table-column>
    </bk-table>

    <!-- 创建/编辑环境变量用弹窗 -->
    <bk-dialog
        v-model="dialog.visible"
        header-position="left"
        width="800"
        :confirm-fn="submitDialog"
        @cancel="cancelDialog"
        :mask-close="false"
    >
        <div slot="header">$[ dialog.type === 'create'?'添加':'编辑' ]环境变量</div>
        <bk-form ref="form" :label-width="140" :model="dialog.form" :rules="rules">
            <bk-form-item label="Key" property="key" :required="dialog.type === 'create'">
                <bk-input v-model="dialog.form.key" :disabled="dialog.type !== 'create'">
                    <template slot="prepend">
                        <div class="group-text">{{system_prefix}}</div>
                    </template>
                </bk-input>
            </bk-form-item>
            <bk-form-item label="Value" property="value" :required="true">
                <bk-input v-model="dialog.form.value"></bk-input>
            </bk-form-item>
            <bk-form-item label="描述" property="description" :required="true">
                <bk-input v-model="dialog.form.description"></bk-input>
            </bk-form-item>
        </bk-form>
    </bk-dialog>
</div>
{% endblock %}

{% block main_script %}
<script>
const system_prefix = {{ system_prefix | to_json }}
const URLRouter = {
    create: decodeURI("{% url 'admin.builtin_config_vars' %}"),
    list: decodeURI("{% url 'admin.builtin_config_vars' %}"),
    detail: decodeURI("{% url 'admin.builtin_config_vars.detail' '${id}' %}"),
}

document.addEventListener('DOMContentLoaded', () => {
    new Vue({
        el: "#builtin-config-var-list",
        delimiters: ['$[', ']'],
        data: function () {
            return {
                data: [],
                dialog: {
                    visible: false,
                    type: '',
                    form: {
                        key: '',
                        value: '',
                        description: '',
                    },
                    row: undefined
                },
                deleteConfirm: {
                    visible: false,
                    row: undefined
                },
                rules: {
                    key: [
                        {
                            required: true,
                            message: '必填项',
                            trigger: 'blur'
                        },
                    ],
                    value: [
                        {
                            required: true,
                            message: '必填项',
                            trigger: 'blur'
                        },
                    ],
                    description: [
                        {
                            required: true,
                            message: '必填项',
                            trigger: 'blur'
                        }
                    ],
                },
            }
        },
        methods: {
            fetchBuiltinEnvList: async function () {
                const el = this.$bkLoading({title: '加载中'})
                try {
                    await this.$http.get(URLRouter.list).then(res => {
                        this.data = res
                    })
                } finally {
                    el.hide = true
                }
            },
            cancelDialog: function () {
                this.dialog.visible = false
            },
            submitDialog: async function () {
                const url = this.dialog.type === 'create' ? URLRouter.create : this.fillUrlTemplate(URLRouter.detail, {row: this.dialog.row});
                let success = true;
                const method = this.dialog.type === 'create' ? 'post' : 'put';
                try {
                    await this.$http[method](url, this.dialog.form);
                } catch (e) {
                    success = false;
                    if (e.response.status === 400) {
                        this.$bkMessage({
                            theme: 'error',
                            message: e.response.data.detail,
                        })
                    }
                }
                if(success) {
                    this.cancelDialog();
                    this.fetchBuiltinEnvList();
                }
            },
            handleCreate: function () {
                this.dialog.type = "create"
                this.dialog.row = undefined
                this.dialog.form = {
                    key: '',
                    value: '',
                    description: '',
                }
                this.$nextTick(() => {
                    // Clear any previous errors
                    this.$refs.form.clearError();
                });
                this.dialog.visible = true
            },
            handleEdit: function (row) {
                this.dialog.type = "edit"
                this.dialog.row = row
                this.dialog.form = { ...row }
                this.$nextTick(() => {
                    // Clear any previous errors
                    this.$refs.form.clearError();
                });
                this.dialog.visible = true
            },
            handleDelete: function (row) {
                this.$bkInfo({
                    title: `确定要删除 ${system_prefix}${row.key}？`,
                    confirmLoading: true,
                    theme: 'danger',
                    confirmFn: async () => {
                        try {
                            await this.deleteRow(row)
                            this.$bkMessage({
                                theme: 'success',
                                message: '删除成功',
                            })
                        } catch (e) {
                            this.$bkMessage({
                                theme: 'error',
                                message: e.response.data.detail,
                            })
                        }
                    }
                })
            },
            deleteRow: async function (row) {
                const url = this.fillUrlTemplate(URLRouter.detail, { row });
                await this.$http.delete(url);

                const index = this.data.findIndex(item => item.key === row.key);
                if (index !== -1) {
                    this.data.splice(index, 1);
                }
            },
            fillUrlTemplate: function (url_template, {row}) {
                if (!row) {
                    row = {}
                }
                return url_template.replace("${id}", row.id)
            },
            addPrefix: function(row, column, cellValue, index) {
                return system_prefix + cellValue
            },
        },
        mounted: function () {
            this.fetchBuiltinEnvList()
        },
    })
})
</script>
<style>
    .bk-alert{
        margin-bottom: 20px;
    }
</style>
{% endblock %}
